﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BudgetRight.Data.Models;

namespace BudgetRight.Data.Adapters
{
    public class CategoryDbAdapter : DbAdapterBase, ICategoryDbAdapter
    {

        public BudgetRightConnection Connection { get; set; }

        public CategoryDbAdapter()
            : this(new BudgetRightConnection()) { }

        private CategoryDbAdapter(BudgetRightConnection connection)
        {
            Connection = connection;
        }

        public ICategoryEntity Save(ICategoryEntity category)
        {
            var entity = category as CategoryEntity;

            if (entity == null)
            {
                throw new ArgumentException("Argument not of expected type.", "category");
            }

            if (entity.Id == null)
            {
                Connection.AddToCategoryEntitySet(entity);
            }

            Connection.SaveChanges();

            return entity;
        }

        public ICategoryEntity GetCategory(int nodeId)
        {
            var node = Connection.CategoryEntitySet.First(n => n.Id == nodeId);

            return (ICategoryEntity)node;
        }

        public IEnumerable<ICategoryEntity> GetCategoryChildren(int nodeId)
        {
            var children = Connection.GetNodeChildren(nodeId);

            return children.Cast<ICategoryEntity>();
        }

        public IEnumerable<ICategoryEntity> GetCategoryDescendants(int nodeId)
        {
            var children = Connection.GetNodeDescendants(nodeId);

            return children.Cast<ICategoryEntity>();
        }

        public IEnumerable<ICategoryEntity> GetCategoryAncestry(int nodeId)
        {
            var ancestors = Connection.GetNodeAncestry(nodeId);

            return ancestors.Cast<ICategoryEntity>();
        }

        public ICategoryEntity GetCategoryParent(int nodeId)
        {
            var parent = Connection.GetNodeParent(nodeId).First();

            return (ICategoryEntity)parent;
        }

    }
}
